<template>
  <el-form :model="registerForm" ref="registerFormRef" label-position="right" label-width="auto" class="register-form">
    <h2>骑手注册</h2>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="registerForm.name" placeholder="请输入姓名" clearable/>
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="registerForm.phone" placeholder="请输入手机号" clearable/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password/>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" show-password/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleRegister" style="width: 100%;">注册</el-button>
    </el-form-item>
    <el-form-item>
      <el-link type="primary" @click="goToLogin">已有账号？去登录</el-link>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from "axios";

const router = useRouter();
const registerFormRef = ref();
const registerForm = reactive({
  name: '',
  phone: '',
  password: '',
  confirmPassword: ''
});

const handleRegister = async () => {
    try {
        // 简单的表单验证
        if (!registerForm.name || registerForm.name.length < 2 || registerForm.name.length > 20) {
            ElMessage.error('姓名长度必须在2到20个字符之间');
            return;
        }
        if (!/^1[3-9]\d{9}$/.test(registerForm.phone)) {
            ElMessage.error('请输入正确的手机号');
            return;
        }
        if (!registerForm.password || registerForm.password.length < 6 || registerForm.password.length > 20) {
            ElMessage.error('密码长度必须在6到20个字符之间');
            return;
        }
        if (registerForm.password !== registerForm.confirmPassword) {
            ElMessage.error('两次输入的密码不一致');
            return;
        }

        // 构建符合后端要求的数据格式
        const registerData = {
            name: registerForm.name,
            phone: registerForm.phone,
            pwd: registerForm.password
        };

        console.log('===== 注册请求开始 =====');
        console.log('请求数据:', registerData);

        const startTime = Date.now();
        try {
            // 使用 axios 直接请求
            const response = await axios.post('/api/rider', registerData);
            const endTime = Date.now();

            console.log(`请求完成，耗时: ${endTime - startTime}ms`);
            console.log('响应数据:', response.data);

            // 适配后端返回的非标准格式
            if (response.data === 1 || (response.data && response.data.success)) {
                ElMessage.success('注册成功，请等待管理员审核');
                router.push('/rider/login');
            } else {
                const errorMessage = response.data && response.data.message ? response.data.message : '注册失败';
                ElMessage.error(errorMessage);
                console.error('注册失败原因:', errorMessage);
            }
        } catch (apiError) {
            const endTime = Date.now();
            console.log(`请求失败，耗时: ${endTime - startTime}ms`);
            throw apiError; // 重新抛出以被外层catch捕获
        }
    } catch (error) {
        console.error('===== 注册请求错误 =====');
        console.error('错误对象:', error);

        // 详细错误信息
        const errorDetails = {
            message: error.message,
            status: error.response?.status,
            statusText: error.response?.statusText,
            data: error.response?.data,
            headers: error.response?.headers,
            config: {
                url: error.config?.url,
                method: error.config?.method,
                data: error.config?.data,
                headers: error.config?.headers,
                timeout: error.config?.timeout
            },
            stack: error.stack
        };

        console.error('错误详情:', JSON.stringify(errorDetails, null, 2));

        // 用户友好的错误信息
        let errorMsg = '注册失败，请稍后重试';
        if (error.response) {
            errorMsg = `请求失败 (${error.response.status}): ${error.response.data?.message || error.response.statusText}`;
        } else if (error.request) {
            errorMsg = '无法连接到服务器，请检查后端服务是否运行正常';
        } else {
            errorMsg = `请求错误: ${error.message}`;
        }

        ElMessage.error(errorMsg);

        // 显示调试信息提示
        ElMessage({
            message: '请打开浏览器控制台查看详细错误信息',
            type: 'warning',
            duration: 5000
        });
    }
};


const goToLogin = () => {
  router.push('/rider/login');
};
</script>

<style scoped>
.register-form {
  max-width: 400px;
  margin: 100px auto;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
 h2 {
  text-align: center;
  margin-bottom: 20px;
}
 .el-form-item {
  margin-bottom: 20px;
}
</style>